package com.hue.springbootshiro.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hue.springbootshiro.domain.Users;
import com.hue.springbootshiro.service.UsersService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Shiro的Realm,必须继承AuthorizingRealm
 */
public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    private UsersService usersService;

    /**
     * 给用户授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authenticationInfo = new SimpleAuthorizationInfo();
        //获取当前登录的用户
        Subject subject = SecurityUtils.getSubject();
        Users users = (Users) subject.getPrincipal();
        //获取当前用户实际用户的权限，并授予给他
        authenticationInfo.addStringPermission(users.getPerms());
        return authenticationInfo;
    }

    /**
     * 认证用户
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取输入的用户名和密码
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        //根据用户名查询用户
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", token.getUsername());
        Users user = usersService.getOne(wrapper);
        if (user == null) {
            //用户名或密码错误
            //返回null是会抛出UnknownAccountException的异常(账户不存在)
            return null;
        }

        //效验输入的密码是否和数据库中的相同
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }
}
